#include "SocketServer.h"

SocketServer::SocketServer(in_port_t port) {
	initialize(INADDR_ANY, port, AF_INET);	
}

SocketServer::SocketServer(in_port_t port, sa_family_t family) {
	initialize(INADDR_ANY, port, family);	
}

SocketServer::SocketServer(in_addr_t address, in_port_t port, sa_family_t family) {
	initialize(address, port, family);	
}

SocketServer::~SocketServer() {
	SocketWrapper::close(_listenfd);
}
	
void SocketServer::start() {
	int connfd;
	struct sockaddr_in clientaddr;
	socklen_t clientlen = sizeof(clientaddr);

	_listenfd = SocketWrapper::socket(_servaddr.sin_family, SOCK_STREAM, 0);
	SocketWrapper::bind(_listenfd, (struct sockaddr*)&_servaddr, sizeof(_servaddr));
	SocketWrapper::listen(_listenfd, 1024);

	while ( 1 ) {
		connfd = SocketWrapper::accept(_listenfd, (struct sockaddr*)&clientaddr, &clientlen);	
		handleAccept(connfd, clientaddr);
	}
}

void SocketServer::initialize(in_addr_t address, in_port_t port, sa_family_t family=AF_INET) {
	bzero(&_servaddr, sizeof(_servaddr));
	_servaddr.sin_family = family;
	_servaddr.sin_addr.s_addr = htonl(address);
	_servaddr.sin_port = htons(port);
}

